//
//  CSSComposeTextView.swift
//  weibo28
//
//  Created by chushushan on 16/5/19.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

//实现看到xib效果
@IBDesignable


//自定义texteView
class CSSComposeTextView: UITextView {

    
    //占位文字
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(17)
        label.textColor = UIColor.lightGrayColor()
        label.numberOfLines = 0
        label.text = "生活不只是苟且 还有诗和远方~"
        
        return label
    }()
    
    //设置占位符 在xib中显示
    @IBInspectable var placeHolder: String? {
        didSet {
        placeHolderLabel.text = placeHolder
        
        }
    
    }
    
    //重写font
       override var font: UIFont? {
        didSet {
            if font == nil {
            
            placeHolderLabel.font = font
            }
        
        }
    }
    
    //重写text
    override var text: String? {
        didSet {
    placeHolderLabel.hidden = hasText()
    
        }
    
    }
    
   
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        
        setupUI()
        
        //监听文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        
    }

    //支持xib
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
        
        //监听文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
    }
    
    
    private func setupUI() {
        
        addSubview(placeHolderLabel)
        
        //使用系统的约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
   
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        placeHolderLabel.x = 5
        placeHolderLabel.y = 8
        
    }
    
    //通知事件
    @objc private func textChange() {
    
    placeHolderLabel.hidden = hasText()
    }
    
    
    //移除通知
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
}
